<template>
  <div class="pagination">
    <h1>{{ startAndEndNumber }}</h1>
    <button @click="$emit('getPageNo',pageNo-1)" :disabled="pageNo==1">上一页</button>
    <button v-show="startAndEndNumber.start>1" @click="$emit('getPageNo',1)">1</button>
    <button v-show="startAndEndNumber.start>2">···</button>
     <!--显示连续页码的地方  v-for与v-if可以一起使用-->
    <button v-for="(page,index) in startAndEndNumber.end" v-if="page>=startAndEndNumber.start" :key="index" :class="{active:pageNo===page}" @click="$emit('getPageNo',page)">{{page}}</button>
    <button v-show="startAndEndNumber.end < totalPage -1 ">···</button>
    <button v-show="startAndEndNumber.end < totalPage" @click="$emit('getPageNo',totalPage)">{{ totalPage }}</button>
    <button @click="$emit('getPageNo',pageNo+1)" :disabled="pageNo===totalPage">下一页</button>
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["total", "pageSize", "pageNo", "pager"],
  computed: {
    //总页码
    totalPage() {
      const { total, pageSize } = this;
      return Math.ceil(total / pageSize);
    },
    //计算连续页码开始与结束数字到底是多少?
    startAndEndNumber() {
      let start = 0,end = 0;
      const { totalPage, pager, pageNo} = this;
      //万一出现:总页数小于等于连续页码数
      if (totalPage <= pager) {
        start = 1;
        end = totalPage;
      } else {
        //总页码大于连续页码
        start = pageNo - parseInt(pager / 2);
        end  = pageNo + parseInt(pager / 2);
        //当前第一页:start-1  非法情况
        //当前第二页:start零
        if(start < 1 ){
           start = 1;
           end = pager;
        }
        //当前第34页: end = 36非法
        //当前第33页: end = 35非法
        if(end > totalPage){
          end = totalPage;
          start = totalPage - pager + 1 
        }
      }
      return {start,end};
    },
  },
  methods: {

  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>